import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';


import { Https } from '../../app/http.service'
import * as city from '../../assets/datas/chinese-cities';


/**
 * Generated class for the NewaddressPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-newaddress',
  templateUrl: 'newaddress.html',
})
export class NewaddressPage {
	private cityColumns: any[]; 
	addressUrl = new Https().Url + "act=goods&op=app_add_address"
	chioceAddress:string;
	
	constructor(public navCtrl: NavController, public navParams: NavParams, public toastCtrl: ToastController) {
		// fetch("../../assets/datas/chinese-cities.json",{
		// 	method:"get",
		// }).then((json)=>{
		// 	json.text().then((data)=>{
		// 		let res = JSON.parse(data);
		// 		this.cityColumns = res; 
		// 	})
			
		// })
		// this.cityColumns = cities;
		this.cityColumns = city.city
		
	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad NewaddressPage');
	}
	//取消地址选择
	cancel($event){

	}
	//地址选择
	change(event,dom){
		let address = [];
		let arr = '';
		// Object.values(event)
		for (let i in event){
			address.push(event[i])
		}
		for (let item of address){
			arr += item.text + " ";
		}
		dom.innerHTML = arr;
		this.chioceAddress = arr;
		
	}
	/* 确定提交
		姓名 input
		电话 input
		省区 innerHTML this.chioceAddress
		详细地址 input
	*/
	submit(name, phone, detailAddress){
		let phoneCheck = /^1(3|4|5|7|8)\d{9}$/.test(phone.value);
		let anmeCheck = /^[\u4e00-\u9fa5]+$/.test(name.value);
		console.log(phoneCheck)
		console.log(anmeCheck)
		console.log(name.value)
		console.log(this.chioceAddress)
		console.log(detailAddress.value)
		console.log(detailAddress.value.length)
		if (phoneCheck && anmeCheck && name.value != '' && this.chioceAddress != null && detailAddress.value != ''){
			fetch(this.addressUrl, {
				method: "post",
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&name= " + name.value + "&phone=" + phone.value + "&province=" + this.chioceAddress + "&detailaddress=" + detailAddress.value,
			}).then((response)=>{
				response.text().then((json)=>{
					if(json != ''){
						let data = JSON.parse(json).datas;
						console.log()
						if (data.code == 0){
							let toast = this.toastCtrl.create({
								message: '添加成功',
								position: "top",
								duration: 3000
							});
							toast.present();
						}
						this.navCtrl.pop();
					}
				})
			}).catch((err)=>{
				let toast = this.toastCtrl.create({
					message: '网络连接错误',
					position: "top",
					duration: 3000
				});
				toast.present();
			})
			
		}else{

			let toast = this.toastCtrl.create({
				message: '出错，请检查输入是否正确',
				position: "top",
				duration: 3000
			});
			toast.present();
		}
		
		
	}

}
